﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web.UI.WebControls;
using TextBox = System.Web.UI.WebControls.TextBox;
using ContractManagementSystem.EntityObjects;
using ContractManagementSystem.BusinessLogicLayer;

namespace ContractManagementSystem.Presentation.TimesheetManagement
{
    public partial class InsertTimesheet : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            CheckUserPermission();

            if(!IsPostBack)
            {
                BindGrid(7);
                BindContractTitle();
                labelResultMessage.Visible = false;
            }
        }
        // bin row on grid
        private void BindGrid(int num)
        {
            DateTime onday = DateTime.Now;
            var items = new List<TimesheetDetailEntity>(4);

            for (int i = 0; i <= num; i++)
            {
                int days = i - num;
                var c = new TimesheetDetailEntity {OnDate = onday.AddDays(days)};
                items.Add(c);
            }

            GridViewTimesheet.DataSource = items;
            GridViewTimesheet.DataBind();
        }

        protected void BindContractTitle()
        {
            foreach (GridViewRow row in GridViewTimesheet.Rows)
            {
                var userName = Session["UserName"].ToString();
                if (row.RowType == DataControlRowType.DataRow)
                {
                    var dropDownListContractNumber = (DropDownList)row.FindControl("DropDownListContractNumber");
                    dropDownListContractNumber.DataSource = ContractLogic.ListActiveContractsByContractor(userName);
                    dropDownListContractNumber.DataTextField = "ContractNumber";
                    dropDownListContractNumber.DataValueField = "ContractNumber";
                    dropDownListContractNumber.DataBind();
                }
            }
        }

        protected bool CheckItemGrid()
        {
            foreach (GridViewRow row in GridViewTimesheet.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    var textDate = (TextBox) row.FindControl("textDate");
                    var textTime = ((TextBox)row.FindControl("textTime"));
                    var textDescription = (TextBox)row.FindControl("textDescription");
                    var dropContractNumber = (DropDownList)row.FindControl("DropDownListContractNumber");

                    var date = DateTime.Parse(textDate.Text, CultureInfo.InvariantCulture);

                    if(string.IsNullOrEmpty(textDate.Text))
                    {
                        labelResultMessage.Text = "Please choose On Date";
                        textDate.CssClass = "CPF-input-error";
                        textDate.Focus();
                        return false;
                    }
                    if(!string.IsNullOrEmpty(textTime.Text))
                    {
                        if (string.IsNullOrEmpty(dropContractNumber.Text))
                        {
                            labelResultMessage.Text = "Please choose contract number";
                            dropContractNumber.CssClass = "CPF-input-error";
                            return false;
                        }
                        if(string.IsNullOrEmpty(textDescription.Text))
                        {
                            labelResultMessage.Text = "Please enter description";
                            textDescription.CssClass = "CPF-input-error";
                            textDescription.Focus();
                            return false;
                        }
                        var time = float.Parse((textTime.Text),CultureInfo.InvariantCulture);
                        if (time < 0 || time > 8)
                        {
                            labelResultMessage.Text = "Time between 1 and 8";
                            textTime.CssClass = "CPF-input-error";
                            textTime.Focus();
                            return false;
                        }

                        //// check date
                        var dataTable = TimesheetLogic.GetDateOfContract(dropContractNumber.SelectedValue);

                        if (dataTable == null)
                        {
                            return false;
                        }

                        var startDate = DateTime.Parse(dataTable.Rows[0]["StartDate"].ToString(), CultureInfo.InvariantCulture);
                        var endDate = DateTime.Parse(dataTable.Rows[0]["EndDate"].ToString(), CultureInfo.InvariantCulture);

                        if (date < startDate || date > endDate)
                        {
                            labelResultMessage.Text = dropContractNumber.SelectedValue + " Date between " + startDate.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture) + " and " + endDate.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);
                            textDate.Focus();
                            textDate.CssClass = "CPF-input-error";
                            return false;
                        }///// end check date 
                    }
                    if(!string.IsNullOrEmpty(textDescription.Text))
                    {
                        if(string.IsNullOrEmpty(textTime.Text))
                        {
                            labelResultMessage.Text = "Please enter time";
                            textTime.CssClass = "CPF-input-error";
                            textTime.Focus();
                            return false;
                        }
                    }
                }
            }
            return true;
        }

        protected void ButtonSaveClick(object sender, EventArgs e)
        {
            labelResultMessage.Visible = true;
            labelResultMessage.Text = string.Empty;

            if (!CheckItemGrid())
                return;

            foreach (GridViewRow row in GridViewTimesheet.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    var dropContractNumber = (DropDownList)row.FindControl("DropDownListContractNumber");
                    var textDate = (TextBox)row.FindControl("textDate");
                    var textTime = ((TextBox)row.FindControl("textTime"));
                    var textDescription = ((TextBox)row.FindControl("textDescription"));

                    var timesheetDate = DateTime.Parse((textDate.Text),CultureInfo.InvariantCulture);
                    
                    if(textDate.Text.Trim().Length==0)
                    {
                        continue;
                    }
                    if (textTime.Text.Trim().Length == 0)
                    {
                        continue;
                    }
                    if(textDescription.Text.Trim().Length==0)
                    {
                        continue;
                    }
                    if(dropContractNumber.Text.Trim().Length==0)
                    {
                        continue;
                    }

                    var timesheetEntity = new TimesheetDetailEntity
                                                          {
                                                              ContractNumber = dropContractNumber.SelectedValue,
                                                              OnDate = timesheetDate,
                                                              Time = float.Parse((textTime.Text),CultureInfo.InvariantCulture),
                                                              Description = textDescription.Text,
                                                              Status ="Pending"
                                                          };
                    string result = TimesheetLogic.InsertTimesheet(timesheetEntity);
                    if(!string.IsNullOrEmpty(result))
                    {
                        labelResultMessage.Text = "Insert Success";
                        Response.Redirect("ListTimesheet.aspx");
                    }
                    else
                    {
                        labelResultMessage.Text = "Insert Failed";
                        // Save event of logging out
                        var userEventEntity = new EventEntity
                        {
                            UserName = CommonLogic.ConvertToString(Session["UserName"]),
                            OnDate = DateTime.Now,
                            EventType=(int)EventTypeList.UserEvent,
                            Description = "User logged out"
                        };

                        EventTracer.SaveEvents(userEventEntity);
                    }
                }
            }
        }

        protected void ButtonResetClick(object sender, EventArgs e)
        {
            labelResultMessage.Text = string.Empty;
            foreach (GridViewRow row in GridViewTimesheet.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    var textTime = ((TextBox)row.FindControl("textTime"));
                    var textDescription = (TextBox)row.FindControl("textDescription");
                    textTime.Text = string.Empty;
                    textDescription.Text = string.Empty;
                }
            }
        }

        // Check user's permissions
        private void CheckUserPermission()
        {
            var userName = CommonLogic.ConvertToString(Session["UserName"]);
            const int functionId = (int)FunctionList.AddTimesheet;

            var urlToCome = Page.Master.ResolveUrl("Presentation/AuthorizationError.aspx");

            AuthorizationChecker.IsValidAuthorization(userName, functionId, Response, urlToCome);
        }

    }
}
